﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using Qiniu.RS;

namespace QiniuAndUeditor.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        //==================for 七牛 ==================================

        public ContentResult QiniuUploadToken()
        {
            var policy = new PutPolicy("你的bucket名字");
            policy.ReturnUrl = "http://localhost:51827/home/QiniuUploadCallBack";
            policy.ReturnBody = "{\"name\": $(fname),\"size\": \"$(fsize)\",\"w\": \"$(imageInfo.width)\",\"h\": \"$(imageInfo.height)\",\"key\":$(etag)}";
            string token = policy.Token();
            return Content(token);
        }

        public JsonResult QiniuUploadCallBack()
        {
            string ret = Request.QueryString["upload_ret"];
            dynamic data = System.Web.Helpers.Json.Decode(DecodeFromBase64("UTF-8", ret));

            //ueditor中的image.js insertBatchMethod会使用下面的参数
            return Json(new { original = data["name"], w = data["w"], h = data["h"], url = data["key"], state = "SUCCESS" }, JsonRequestBehavior.AllowGet);

        }

        private string DecodeFromBase64(string encode, string code)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(code);
            try
            {
                decode = Encoding.GetEncoding(encode).GetString(bytes);
            }
            catch
            {
                decode = code;
            }
            return decode;
        }

        //==============================================================

    }
}
